package org.yunai.yfserver.persistence.async;

import com.alibaba.fastjson.JSON;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.slf4j.Logger;
import org.yunai.yfserver.async.IIoSerialOperation;
import org.yunai.yfserver.common.LoggerFactory;
import org.yunai.yfserver.common.constants.CommonErrorLogInfo;
import org.yunai.yfserver.persistence.PersistenceObject;
import org.yunai.yfserver.persistence.orm.Entity;
import org.yunai.yfserver.persistence.orm.mybatis.DeleteMapper;

/**
 * 删除对象到数据库操作
 * User: yunai
 * Date: 13-4-9
 * Time: 下午11:10
 */
public class DeletePersistenceObjectOperation<E extends Entity<?>, P extends PersistenceObject<?, E>> implements IIoSerialOperation {
    private static final Logger LOGGER = LoggerFactory.getLogger(LoggerFactory.Logger.async, DeletePersistenceObjectOperation.class);

    private final P persistenceObject;
    private final E entity;
    private final DeleteMapper<E> mapper;

    public DeletePersistenceObjectOperation(P persistenceObject, DeleteMapper<E> mapper) {
        this.persistenceObject = persistenceObject;
        this.entity = persistenceObject.toEntity();
        this.mapper = mapper;
    }

    @Override
    public State doStart() {
        return State.STARTED;
    }

    @Override
    public State doIo() {
        try {
            mapper.delete(entity);
        } catch (Exception e) {
            LOGGER.error("[doIo][{}][{}] entity[{}] dao[{}] error[{}].", CommonErrorLogInfo.DB_OPERATE_FAIL, "DELETE",
                    JSON.toJSONString(entity), mapper, ExceptionUtils.getStackTrace(e));
            return State.FINISHED;
        }
        return State.IO_DONE;
    }

    @Override
    public State doFinish() {
        return State.FINISHED;
    }

    @Override
    public Integer getSerialKey() {
        return persistenceObject.getUnitId();
    }
}
